<template>
  <div class="app-container">


    <div style="margin-bottom: 20px;text-align: right;">

      <el-button
        size="small"
        :disabled="!editableTabs.length > 0"
        @click="submitTabData()"
      >
        添加数据
      </el-button>


      <el-button
        size="small"
        icon="el-icon-plus"
        @click="addTab(editableTabsValue)"
      >
      </el-button>
    </div>


    <div class="mytabs-block">

      <el-tabs
        v-model="editableTabsValue"
        tab-position="left"
        closable
        @tab-remove="removeTab"
        @tab-click="handleClickTab"
      >
        <el-tab-pane
          v-for="item in editableTabs"
          :key="item.name"
          :label="item.title"
          :name="item.name"
        >
          <!-- {{ item.content }} -->

          <!-- vxe检索数据组件 -->
          <search-form
            ref="searchForm"
            :stitchTypeOptions="stitchTypeOptions"
            :stitchNameOptions="stitchNameOptions"
            :formSearchData.sync="formSearchData"
            @stitchTypeChangeEmit="stitchTypeChangeEmit"
            @stitchNameChangeEmit="stitchNameChangeEmit"
          >
          </search-form>

          <!-- 表格组件 -->
          <ex-base-table
            ref="exBaseTable2"
            :tableColumn="tableColumn"
            :tableData="tableData"
            :loading.sync="loading"
            :isVxeColSeq="false"
            :isVxeToolbar="false"
            :isVxeCheckbox="true"
            :isVxeHandleS="false"
            @checkboxClickEmit="checkboxClickEmit"
          >


          </ex-base-table>

        </el-tab-pane>
      </el-tabs>

    </div>

  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// import PageHeaderLayout from '@/layouts/PageHeaderLayout'
// import ApeDrawer from '@/components/ApeDrawer'
// import { mapGetters } from 'vuex'
import XEUtils from 'xe-utils'

import {addSplicingzi, findcvlist, findcvtype, findtermlist,} from './service/baseApi'
// 基础表格组件
import ExBaseTable from './components/ExBaseTable'


// 检索表单
import SearchForm from './components/SearchForm'


export default {
  name: 'vxe-basetable',
  mixins: [],
  components: {
    ExBaseTable,
    SearchForm,
  },
  props: {
    /* 当前行数据 */
    currentRow: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  // 定义属性
  data() {
    return {

      //tabs
      editableTabsValue: '1',
      editableTabs: [
        {
          title: 'New Tab',
          name: '1',
          content: ''
        }
      ],
      tabIndex: 1,

      // tabs组件所需要的提交数据（当选择两个之后）
      editableTabsSubmitData: {
        // 'searchkey1_searchkey2': {  //tabs-name=1  key职位
        //   'formSearchData_searchkey1': '第一个搜索值',
        //   'formSearchData_searchkey2': '第二个搜索值',
        //   'tabdata': [
        //     // 对应表格的值
        //   ],
        //   'isInit': false   //数据是否已经初始化过，如果没有则直接删除标签
        // }
      },

      // 曲线拼接名称和类型keyValue对应
      stitchTypeKV: {},
      stitchNameKV: {},
      editableTabsSubmitDataKey: '',
      editableTabsSubmitDataValue: '',

      // 检索条件
      formSearchData: {
        stitch_type: '',
        stitch_name: ''
      },

      stitchTypeOptions: [], //拼接类型选项
      stitchNameOptions: [], //拼接名称选项


      /* 表格相关 */
      tableColumn: [], // 表格字段
      loading: false, //表格loading特效
      tableData: [],  //表格数据


    } //datareturn-end

  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {},
  // 监控data中的数据变化
  watch: {
    tableData() {
      this.tableDataChange()
    },

  },
  // 方法集合
  methods: {

    submitTabData() {

      let sTabData = {}
      // 判断tabs是否有页签，如果有判断是否初始化值
      if (this.editableTabs.length > 0 && this.verifyEditableTabsDataAll()) {
        this.$message.warning('存在数据不完善页签,请先完善页签数据或删除该页签！');
      } else {
        if (Object.getOwnPropertyNames(this.editableTabsSubmitData).length > 0) {
          Object.values(this.editableTabsSubmitData).forEach((item) => {
            if (item.tabData.length > 0) {
              sTabData[`${item.formSearchData_stitch_type}_${item.formSearchData_stitch_name}`] = item.tabData.map((i) => i.term_code).join(',')
            }
          })
          this.addSplicingziApi(sTabData)
        }

      }
    },
    //标签增加
    addTab(targetName) {

      // 判断tabs是否有页签，如果有判断是否初始化值
      if (this.editableTabs.length > 0 && this.verifyEditableTabsDataAll()) {
        this.$message.warning('存在数据不完善页签,请先完善页签数据或删除该页签！');
      } else {
        this.initTabDataFormTableData()
        // 判断是否存在没有设置标签数据的标签，存在不可以创建
        let newTabName = ++this.tabIndex + '';
        this.editableTabs.push({
          title: 'New Tab',
          name: newTabName,
          content: ''
        });
        this.editableTabsValue = newTabName;
      }


    },
    //标签移除，并删除对应数据
    removeTab(targetName) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
              // 如果删除当前页签，切换页签后需要重置切换后的页签数据
              this.switchTabResetData(activeName)
            }
          }
        });
      }
      this.editableTabsValue = activeName;

      this.editableTabs = tabs.filter(tab => tab.name !== targetName);
      // 删除页签生成的表单数据
      this.deleteEditableTabsData(targetName)


    },
    handleClickTab(tab, event) {
      this.verifyEditableTabsDataAll()
      this.switchTabResetData(tab.name)

    },
    // 修改当前tab的title
    editCurrentTabTitle(editableTabsSubmitDataValue, editableTabsSubmitDataKey) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      tabs.forEach((tab, index) => {
        if (tab.name === activeName) {
          tab.title = editableTabsSubmitDataValue
          tab.content = editableTabsSubmitDataKey
        }
      });
    },
    //  初始化拼接曲线类型和拼接曲线名称
    initTabDataFormTableData() {
      this.formSearchData.stitch_type = ''
      this.formSearchData.stitch_name = ''
      this.tableData = []
    },


    //初始化对应标签数据
    initTabData() {

      this.editableTabsSubmitDataKey = `${this.formSearchData.stitch_type}_${this.formSearchData.stitch_name}`
      this.editableTabsSubmitDataValue = `${this.stitchTypeKV[`${this.formSearchData.stitch_type}`]}_${this.stitchNameKV[`${this.formSearchData.stitch_name}`]}`
      this.editCurrentTabTitle(this.editableTabsSubmitDataValue, this.editableTabsSubmitDataKey)

      if (!this.editableTabsSubmitData[`${this.editableTabsValue}`]) {
        this.$set(this.editableTabsSubmitData, `${this.editableTabsValue}`, {})
        this.$set(this.editableTabsSubmitData[`${this.editableTabsValue}`], 'formSearchData_stitch_type', this.formSearchData.stitch_type)
        this.$set(this.editableTabsSubmitData[`${this.editableTabsValue}`], 'formSearchData_stitch_name', this.formSearchData.stitch_name)
        this.$set(this.editableTabsSubmitData[`${this.editableTabsValue}`], 'tabData', [])
      }


    },
    // tab切换时from和table数据回显
    async switchTabResetData(tabName) {

      await this.initTabDataFormTableData()
      if (this.editableTabsSubmitData[`${tabName}`]) {
        await this.$set(this.formSearchData, 'stitch_type', this.editableTabsSubmitData[`${tabName}`].formSearchData_stitch_type)
        await this.$set(this.formSearchData, 'stitch_name', this.editableTabsSubmitData[`${tabName}`].formSearchData_stitch_name)
      }


    },
    tableDataChange() {

      if (this.tableData.length > 0) {
        let checkTableData = []
        let tabName = this.editableTabsValue;
        // 如果有选中数据
        if (this.editableTabsSubmitData[`${tabName}`].tabData.length > 0) {
          // 刷选中当前列表中被选中数据
          XEUtils.arrayEach(this.editableTabsSubmitData[`${tabName}`].tabData, (item, key) => {

            const _index = this.tableData.findIndex((val) => {
              return val.term_code === item.term_code
            })
            if (this.tableData[`${_index}`]) {
              checkTableData.push(this.tableData[`${_index}`])
            }

          })


          // 渲染勾选状态
          this.$nextTick(() => {
            this.$refs.exBaseTable2[`${this.editableTabsValue - 1}`].$refs.xTable.setCheckboxRow(checkTableData, true)
          })
        }
      }
    },

    // 判断当前页签是否编辑完整（切换，添加，删除 时调用）
    verifyEditableTabsData() {
      let tabName = this.editableTabsValue;
      if (
        !this.editableTabsSubmitData[`${tabName}`]
        ||
        !(this.editableTabsSubmitData[`${tabName}`].tabData.length > 0)
      ) {
        return false
      }
      return true
    },
    // 判断当前页签是否初始化数据
    verifyEditableTabsDataInit() {
      let tabName = this.editableTabsValue;
      if (
        !this.editableTabsSubmitData[`${tabName}`]
      ) {
        return false
      }
      return true
    },
    // 判断所有页签数据是否有不完整的数据
    verifyEditableTabsDataAll() {
      let tabs = this.editableTabs;
      return tabs.some((tab, index) => {
        return !this.editableTabsSubmitData[`${tab.name}`]
      });
    },
    // 删除页签功能
    deleteEditableTabsData(targetName) {
      this.$delete(this.editableTabsSubmitData, `${targetName}`)
    },

    checkboxClickEmit(records) {
      this.$set(this.editableTabsSubmitData[`${this.editableTabsValue}`], 'tabData', records)
    },
    // 格式化多选row
    formattingCheckboxRow(row) {
      delete row['_XID']
      // 生成唯一值
      row['cid'] = JSON.stringify(row)
      return row
    },

    /* API数据操作相关 */
    findfindcvtype() {
      findcvtype().then(({data}) => {
        this.stitchTypeOptions = XEUtils.map(data.rows, (item) => {
          this.stitchTypeKV[`${item.code}`] = item.name
          return {
            value: item.code,
            label: item.name
          }
        })
      })
    },
    findfindcvlist(stitchTypeCode) {
      findcvlist({
        code: stitchTypeCode
      }).then(({data}) => {
        this.stitchNameOptions = XEUtils.map(data.rows, (item) => {
          this.stitchNameKV[`${item.id}`] = item.cv_name
          return {
            value: item.id,
            label: item.cv_name
          }
        })
      })
    },
    findfindtermlist() {
      this.loading = true
      findtermlist({
        ...this.formSearchData
      }).then(({data}) => {
        this.tableData = data.rows
        setTimeout(() => {
          this.loading = false
        }, 0.5 * 1000)
      })
    },
    addSplicingziApi(sTabData) {
      addSplicingzi({
        mid: this.currentRow.id,
        ...sTabData
      }).then(({data}) => {
        // 添加处理后的结果
        this.initTabDataFormTableData()
        this.initTabsDatas()
        this.editableTabsSubmitData = {}
        this.$emit('addSplicingziApiEmit')
      })
    },
    // 初始化tabs插件所需参数
    initTabsDatas() {
      this.editableTabsValue = '1'
      this.editableTabs = [
        {
          title: 'New Tab',
          name: '1',
          content: ''
        }
      ]
      this.tabIndex = 1
    },
    stitchTypeChangeEmit(stitchTypeCode) {

      this.$set(this.formSearchData, 'stitch_name', '')
      this.stitchNameOptions = []
      this.findfindcvlist(stitchTypeCode)
    },
    // 查询期限点
    stitchNameChangeEmit() {
      if (this.formSearchData.stitch_name && this.formSearchData.stitch_type) {
        // 初始化提交数据
        this.initTabData()
        // 初始化期限点提交数据
        this.findfindtermlist()
      }
    },

    /* 表格组件相关 */
    // 初始化表格字段
    initTableCols() {
      const tabCols = [  //动态增加的字段 传进来的
        {field: 'term_name', title: '期限名称'},
        {field: 'term_code', title: '期限点'},
      ]
      this.tableColumn = tabCols;
    },


  }, //method-end
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // 初始化表格字段
    this.initTableCols()
    this.findfindcvtype()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
  beforeCreate() {
  }, // 生命周期 - 创建之前
  beforeMount() {
  }, // 生命周期 - 挂载之前
  beforeUpdate() {
  }, // 生命周期 - 更新之前
  updated() {
  }, // 生命周期 - 更新之后
  beforeDestroy() {
  }, // 生命周期 - 销毁之前
  destroyed() {
  }, // 生命周期 - 销毁完成
  activated() {
  }, // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang='scss' scoped>

.mytabs-block {
  border: 1px solid #ebebeb;
  border-radius: 3px;
  transition: .2s;
  margin-bottom: 24px;
}

</style>
